package com.alfayun.fiscalriskanalysis.report;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alfayun.fiscalriskanalysis.importer.ImportResult;
import com.alfayun.fiscalriskanalysis.importer.ImporterFactory;

@Service
public class ReportService {
	
	@Autowired
	private ReportRepository repository;
	
	@Autowired
	private CellService cellService;

	public List<Report> list() {
		return repository.findAll();
	}

	public Report queryById(int id) throws NoSuchReportException {
		return repository.findById(id).orElseThrow(NoSuchReportException::new);
	}

	public Report newReport(Report report) {
		return Report.newReport(repository, report);
	}

	public void deleteReport(int id) {
		repository.deleteById(id);
	}

	public Report modifyReport(int id, Report report) throws NoSuchReportException {
		Optional<Report> row = repository.findById(id);

		if (row.isPresent()) {
			return repository.save(report);
		}

		throw new NoSuchReportException();
	}

	public ImportResult importReprot(InputStream inputStream, int reportId) throws NoSuchReportException, IOException {
		Report report = repository.findById(reportId).orElseThrow(NoSuchReportException::new);
		return ImporterFactory.getImporter(report.getReportSpec().reportIndex).importReport(inputStream, report, cellService);
	}

    

}
